package org.example.ttl;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.util.HashMap;
import java.util.Map;

public class TopicsConsumerRejectTest {


    public static final String EXCHANGE_NAME = "normal_exchange4";

    public static final String DEAD_EXCHANGE = "dead_exchange4";


    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        //声明正常类型的交换机
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);
        String queueName = "normal-queue4";
        Map<String, Object> params = new HashMap<>();

        params.put("x-dead-letter-exchange", DEAD_EXCHANGE);
        params.put("x-dead-letter-routing-key", "black");
        channel.queueDeclare(queueName, false, false,
                false, params);


        //将队列绑定到交换机
        channel.queueBind(queueName, EXCHANGE_NAME, "orange");


        //声明死信类型的交换机
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.TOPIC);
        String deadQueue = "dead-queue2";
        channel.queueDeclare(deadQueue, false, false,
                false, null);

        //将死信队列绑定到交换机
        channel.queueBind(deadQueue, DEAD_EXCHANGE, "black");


        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            if ("消息5".equals(message)) {
                //requeue=false
                channel.basicReject(delivery.getEnvelope().getDeliveryTag(), false);
                return;
            }
            String exchangeName = delivery.getEnvelope().getExchange();
            System.out.println(" [x] Received '" +
                    delivery.getEnvelope().getRoutingKey() + "':'" + message + "'" + ",from exchange=" + exchangeName);
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        };
        channel.basicConsume(queueName, false, deliverCallback, consumerTag -> {
        });
    }
}
